package org.redmagic.client.prototype;

import java.io.ByteArrayInputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import com.google.common.collect.Lists;

public class RMFileResolver {

	private final String resolvedConfigurationFileContents;

	public RMFileResolver(String magicConfigFileName) {
		this(magicConfigFileName, Lists.<String>newArrayList());
	}
	
	public RMFileResolver(String magicConfigFileName, List<String> setupFileNames) {
		String[] magicConfigSetupFileNames = (setupFileNames != null ? (String[]) setupFileNames.toArray() : new String[0]);
		this.resolvedConfigurationFileContents = RMConfigurationIntializer.resolveConfigurationFile(magicConfigFileName, magicConfigSetupFileNames);
	}
	
	public String getResolvedFileContents() {
		return resolvedConfigurationFileContents;
	}
	
	public Document getResolvedFileContentsAsDocument() {
		try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder docBuilder = factory.newDocumentBuilder();
            Document configurationDocument = docBuilder.parse(new ByteArrayInputStream(resolvedConfigurationFileContents.getBytes()));
            return configurationDocument;            
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}